package com.example.demo.modules.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.example.demo.common.util.EncryptUtils;
import com.example.demo.modules.dao.UserMapper;
import com.example.demo.modules.service.UserService;
import com.example.demo.modules.vo.UserVo;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Override
	@Transactional
	public void createUser(UserVo userVo) {
		userVo.setUserPass(EncryptUtils.md5(userVo.getUserPass(), userVo.getUserSalt()));
		userVo.setCreateTime(new Date());
		userVo.setUpdateTime(new Date());
		userMapper.insert(userVo);
	}

	@Override
	public void updateUser(UserVo userVo) {
		userMapper.update(userVo, null);
	}

	@Override
	public UserVo findUserById(String id) {
		return userMapper.selectById(id);
	}

	@Override
	public UserVo findUserByName(String userName) {
		Map<String, Object> param = new HashMap<>();
		param.put("user_name", userName);
		List<UserVo> userList = userMapper.selectByMap(param);
		if (userList != null && !userList.isEmpty()) {
			return userList.get(0);
		}
		return null;
	}

	@Override
	public boolean checkUserNameExists(String userName) {
		EntityWrapper<UserVo> entityWrapper = new EntityWrapper<>();
		entityWrapper.where("user_name = {0}", userName);
		Integer count = userMapper.selectCount(entityWrapper);
		if (count != null && count > 0) {
			return true;
		}
		return false;
	}

}
